import minecraft_launcher_lib
import os
import time

from WareHouseCore import *

class accountManager:

    # 私有函数定义
    def __checkUserAccount(self, commitWareHouse:wareHouse):
        for i in range(len(commitWareHouse.minecraftAccounts['accountList'])):
            if not minecraft_launcher_lib.account. \
                    validate_access_token(commitWareHouse.minecraftAccounts['accountList'][i]['playerAccessToken']):
                print(f" * ------- Error(No. {i})")
                print(f" * & Player email({commitWareHouse.minecraftAccounts['accountList'][i]['playerLoginEmail']})")
                print(f" * & Player name({commitWareHouse.minecraftAccounts['accountList'][i]['playerUsername']})")
                print(f" * & Player UUID({commitWareHouse.minecraftAccounts['accountList'][i]['playerUUID']})")
                print(f" * & Status: Cannot certification access token, please relogin (；´Д`A !")
                reloginPassword = input(f" * & -- "
                                        f"{commitWareHouse.minecraftAccounts['accountList'][i]['playerLoginEmail']}'s "
                                        f"password --> ")
                # 重新登陆
                loginData = minecraft_launcher_lib.account.login_user(
                    commitWareHouse.minecraftAccounts['accountList'][i]['playerLoginEmail'],
                    reloginPassword
                )

                # 测试账号
                if len(loginData) != 2:
                    accountData = {
                        "playerLoginEmail": commitWareHouse.minecraftAccounts['accountList'][i]['playerLoginEmail'],
                        "playerUsername": loginData["selectedProfile"]["name"],
                        "playerUUID": loginData["selectedProfile"]["id"],
                        "playerAccessToken": loginData["accessToken"],
                        "playerClientToken": loginData["clientToken"]
                    }

                    commitWareHouse.minecraftAccounts["accountList"][i] = accountData

                    print(" * & Login complete.")
                    print(f" * & Your account player name({accountData['playerUsername']})")
                    print(f" * & Your account player uuid({accountData['playerUUID']})")
                    input(" * & Press Enter key continue... ")

                elif reloginPassword != "":
                    print(" * & Cannot certification... ")
                    print(" * & Please check your network and username or password.")
                    print(" * & This account well be remove")
                    print(" * & You can use ADD command readd it (^○^) !")
                    print(" * & Or now press <Control + C> kill this program, and restart this progarm")
                    print(" * & to reinput password (´▽｀) !")
                    input(" * & Press Enter key remove account and continue... ")

                    # 移除
                    # 移除
                    del commitWareHouse.minecraftAccounts["accountList"][i]

                    # 将 accessToken 更新为无效
                    minecraft_launcher_lib.account.invalidate_access_token(
                        commitWareHouse.minecraftAccounts['accountList'][i]['playerAccessToken'],
                        commitWareHouse.minecraftAccounts['accountList'][i]['playerClientToken']
                    )

                    print(" * $ Removed... ")
                    print(" * $ Exit LitsMine save this change... ")
                    print(" * $ Heaven is reincarnation, who is forgiven by heaven ?")
                    input(" * & Press Enter key continue --> ")

                else:
                    print(" * & Cannot certification... ")
                    print(" * & You not input password.")
                    print(" * & This account well be remove")
                    print(" * & You can use ADD command readd it (^○^) !")
                    print(" * & Or now press <Control + C> kill this program, and restart this progarm")
                    print(" * & to reinput password (´▽｀) !")
                    input(" * & Press Enter key remove account and continue... ")

                    # 移除
                    # 移除
                    del commitWareHouse.minecraftAccounts["accountList"][i]

                    # 将 accessToken 更新为无效
                    minecraft_launcher_lib.account.invalidate_access_token(
                        commitWareHouse.minecraftAccounts['accountList'][i]['playerAccessToken'],
                        commitWareHouse.minecraftAccounts['accountList'][i]['playerClientToken']
                    )

                    print(" * $ Removed... ")
                    print(" * $ Exit LitsMine save this change... ")
                    print(" * $ Heaven is reincarnation, who is forgiven by heaven ?")
                    input(" * & Press Enter key continue --> ")

    def __searchAccount(self, searchCondition:str, searchModeName:str, commitWareHouse:wareHouse):
        print(f" * $ Enter search data | Mode({searchModeName}) | Enter null string exit")
        searchContents = input(" * & --> ")

        # 判断是否输入空字符
        if searchContents == "":
            print(" * & Auto exit")
            print(" * & Press Enter key continue... "); return

        # 创建计数器
        nowFoundSum = 0
        nowSearchTrySum = 0

        # 创建找到账号列表
        foundAccountList = []

        # 记录开始时间
        allFoundStartTime_clock = time.clock()

        # 搜索
        print(" * ------- Start search (≧▽≦) !")
        for i in range(len(commitWareHouse.minecraftAccounts["accountList"])):
            nowFoundStartTime_clock = time.clock()
            nowSearchTrySum += 1

            if searchContents in commitWareHouse.minecraftAccounts["accountList"][i][searchCondition]:
                nowFoundSum += 1
                nowFoundEndTime_clock = time.clock()
                nowFoundUsingTime = nowFoundEndTime_clock - nowFoundStartTime_clock
                nowFoundAllUsingTime = nowFoundEndTime_clock - allFoundStartTime_clock

                foundAccountList.append(commitWareHouse.minecraftAccounts["accountList"][i])

                print(" * @ Now found --> %d" % nowFoundSum)
                print(" * @ Now try count --> %d" % nowSearchTrySum)
                print(" * @ Found is result using --> %.2f" % nowFoundUsingTime)
                print(" * @ Now found using time --> %.2f" % nowFoundAllUsingTime)
                print(" * ------- Found next (^○^) !")

            else:
                continue

        print(" * & Check account list... ")
        print(" * ------- Complete search (´▽｀) ~")

        # 处理数据
        allFoundEndTime_clock = time.clock()
        allFoundUsingTime = allFoundEndTime_clock - allFoundStartTime_clock

        # 什么都没找到
        if nowFoundSum == 0:
            print(" * $ Ops !")
            print(" * $ Try count(%d)" % nowSearchTrySum)
            print(" * $ Using tiem(%.2f)" % allFoundUsingTime)
            print(" * $ No account found !")
            print(" * $ Please sure your Enter search ~")

        # 正常情况
        else:
            input(" * $ Press Enter show found account list... ")
            os.system("clear")

            # 打印列表
            print(" * -------------------------- Account list -------------------------- *")
            print(" * $ Print list... ")

            for i in range(len(foundAccountList)):
                print(f" * ------- Found. {i} ")
                # 打印信息
                print(f" * & Player email({foundAccountList[i]['playerLoginEmail']})")
                print(f" * & Player name({foundAccountList[i]['playerUsername']})")
                print(f" * & Player UUID({foundAccountList[i]['playerUUID']})")
                print(f" * & Player password(** You don't have access **)")

            # 完成
            print(" * ------- End print")

    def __removeAccount(self, removeCondition:str, removeModeName:str, commitWareHouse:wareHouse):
        print(f" * $ Enter search data | Mode({removeModeName}) | Enter null string exit")
        print(f" * $ Tips: Only search mode support fuzzy search (つД`)ノ !")
        searchContents = input(" * & --> ")

        # 判断是否输入空字符
        if searchContents == "":
            print(" * & Auto exit")
            print(" * & Press Enter key continue... "); return

        # 记录开始计算用时
        finderProcessStart_Clock = time.clock()

        # 设置没找到的 bool
        foundAccount = False

        for i in range(len(commitWareHouse.minecraftAccounts["accountList"])):

            # 找到
            if commitWareHouse.minecraftAccounts["accountList"][i][removeCondition] == searchContents:
                # 处理部分
                # 计算运用时间
                finderProcessEnd_Clock = time.clock()
                finderProcessUsing_Clock = finderProcessEnd_Clock - finderProcessStart_Clock

                # 获取账号信息
                findAccountInfo = commitWareHouse.minecraftAccounts["accountList"][i]

                print(
                    f" * ------- Found({findAccountInfo['playerUsername']})(%.2f s)!" % finderProcessUsing_Clock)
                print(f" * #-# Account info")
                print(f" * & Account player name({findAccountInfo['playerUsername']})")
                print(f" * & Account player email({findAccountInfo['playerLoginEmail']})")
                print(f" * & Account player UUID({findAccountInfo['playerUUID']})")
                print(f" * #-# Warning")
                print(f" * $ You want remove this account?")
                print(f" * $ Please Enter your result([Y] or [N|Enter])")
                userRemoveAnswer = input(f" * $ --> ").upper()

                # 判断是否移除
                if userRemoveAnswer == "Y":
                    # 移除
                    del commitWareHouse.minecraftAccounts["accountList"][i]

                    # 将 accessToken 更新为无效
                    minecraft_launcher_lib.account.invalidate_access_token(
                        findAccountInfo['playerAccessToken'], findAccountInfo['playerClientToken']
                    )

                    print(" * $ Removed... ")
                    print(" * $ Exit LitsMine save this change... ")
                    print(" * $ Heaven is reincarnation, who is forgiven by heaven ?")
                    input(" * & Press Enter key continue --> ")

                else:
                    print(" * $ Ok, now operating is be canceled")
                    print(" * $ Be careful next time !")
                    input(" * & Press Enter key continue --> ")

                # 离开
                foundAccount = True; break

            # 没找到
            else:
                foundAccount = False; continue

        if not foundAccount:
            # 没找到信息
            print(" * ------- Cannot found... ")
            print(" * $ Sorry, we cannot found, please check your enter contents is sure.")
            input(" * & Press Enter key continue --> ")

    # 外部函数定义
    def welcomeTitle(self):
        print("  * ==================================================== *")
        print("  |                        Account                       |")
        print("  |            _                             _           |")
        print("  |           / \   ___ ___ ___  _   _ _ __ | |_         |")
        print("  |          / _ \ / __/ __/ _ \| | | | '_ \| __|        |")
        print("  |         / ___ \ (_| (_| (_) | |_| | | | | |_         |")
        print("  |        /_/   \_\___\___\___/ \__,_|_| |_|\__|        |")
        print("  |                                                      |")
        print("  * ------------- Press Enter key continue ------------- *")
        input("  [ --> ")

        os.system("clear")

    def coreUI(self, fristRun:bool, commitWareHouse:wareHouse):

        # 第一次启动处理
        if fristRun:
            print("  * -------------------- Welcome ------------------- *")
            print("  |  Welcome use LitsMine account manager, you know  |")
            print("  |  play minecraft need a minecraft account, please |")
            print("  |  in there to login your minecraft account.       |")
            print("  |  We will not steal your account, please believe  |")
            print("  |  us.                                             |")
            print("  * ----------- Press Enter key continue ----------- *")
            input("  [ -->")

            os.system("clear")

            print("  * [LitsMine] Please Enter your minecraft account email.")
            loginEmail = input("  [ --> "); os.system("clear")
            print("  * [LitsMine] Please Enter your minecraft account password")
            loginPassword = input("  [ --> "); os.system("clear")
            print("  * [LitsMine] Login... ")

            loginData = minecraft_launcher_lib.account.login_user(loginEmail, loginPassword)

            # 测试账号
            if len(loginData) != 2:
                accountData = {
                    "playerLoginEmail": loginEmail,
                    "playerUsername": loginData["selectedProfile"]["name"],
                    "playerUUID": loginData["selectedProfile"]["id"],
                    "playerAccessToken": loginData["accessToken"]
                }

                commitWareHouse.minecraftAccounts["accountList"].append(accountData)

                print("  * [LitsMine] Login complete.")
                print(f"  * [LitsMine] Your account player name({accountData['playerUsername']})")
                print(f"  * [LitsMine] Your account player uuid({accountData['playerUUID']})")
                input("  * [LitsMine] Press Enter key continue... ")

            else:
                print("  * [LitsMine] Cannot certification... ")
                print("  * [LitsMine] Please check your network and username or password.")
                print("  * [LitsMine] Stop add account to account list.")
                print("  * [LitsMine] You can in main menu type <3> to back accountManager add account.")
                input("  * [LitsMine] Press Enter key continue... ")

        else:

            # 打印列表
            print(" * -------------------------- Account list -------------------------- *")
            print(" * $ Print list... ")
            print(" * $ Check list... ")
            if len(commitWareHouse.minecraftAccounts["accountList"]) != 0:
                for i in range(len(commitWareHouse.minecraftAccounts["accountList"])):
                    # 测试
                    # 测试 accessToken 是否正常
                    self.__checkUserAccount(commitWareHouse)

                    # 打印
                    # 打印 ID
                    print(f" * ------- No. {i}")
                    # 打印信息
                    print(f" * & Player email({commitWareHouse.minecraftAccounts['accountList'][i]['playerLoginEmail']})")
                    print(f" * & Player name({commitWareHouse.minecraftAccounts['accountList'][i]['playerUsername']})")
                    print(f" * & Player UUID({commitWareHouse.minecraftAccounts['accountList'][i]['playerUUID']})")
                    print(f" * & Player password(****)")
                print(" * ------- End print")
            else:
                print(" * $ No account.")
                print(" * $ You can use ADD command add a new account")

            while True:
                print(" * & Command area")
                print(" * ---------------------------- Commands ---------------------------- *")
                getCommand = input(" * [LitsMine] Command area(Enter help show HelpDocs): ")

                # 忽略大小写 / 统一大小写
                getCommand = getCommand.upper()

                os.system("clear")

                if getCommand == "HELP":
                    print(" * -------------------------- Help Doc -------------------------- *")
                    print(" | == Commands                                                    |")
                    print(" | & == HELP                                                      |")
                    print(" |      Show this document                                        |")
                    print(" | & == ADD                                                       |")
                    print(" |      Add a account                                             |")
                    print(" | & == REMOVE <Mode> <PlayerName/PlayerEmail/PlayerUUID>         |")
                    print(" |      Remove a account.                                         |")
                    print(" |      Mode: EMAIL/NAME/UUID/NO                                  |")
                    print(" |      Mode(EMAIL): Argv[2]: Need remove account player email    |")
                    print(" |      Mode(NAME): Argv[2]: Need remove account player name      |")
                    print(" |      Mode(UUID): Argv[2]: Need remove account player uuid      |")
                    print(" | & == search <Mode> <Contents>                                  |")
                    print(" |      Search a account                                          |")
                    print(" |      Inherit REMOVE command search system                      |")
                    print(" | & == LIST                                                      |")
                    print(" |      Show account list                                         |")
                    print(" | & == QUIT                                                      |")
                    print(" |      Back main menu / Quit accountManager                      |")
                    print(" | & == Other                                                     |")
                    print(" |      Enter other command                                       |")
                    print(" |      System auto exit                                          |")
                    print(" | & -- Tips                                                      |")
                    print(" |      Please don't Enter parameter in command area              |")
                    print(" |      Please frist Enter command                                |")
                    print(" * -------------------------- Help End -------------------------- *")
                    input(" * [LitsMine] Press Enter key continue... "); os.system("clear")

                elif getCommand == "ADD":
                    print(" * ---------------------------- Add ---------------------------- *")
                    print(" * $ Please Enter your minecraft account email")
                    loginEmail = input(" * $ --> "); os.system("clear")
                    print(" * ---------------------------- Add ---------------------------- *")
                    print(" * $ Please Enter your minecraft account password")
                    loginPassword = input(" * $ --> "); os.system("clear")

                    print(" * ---------------------------- Add ---------------------------- *")
                    print(" * & Login... ")

                    loginData = minecraft_launcher_lib.account.login_user(loginEmail, loginPassword)

                    # 测试账号
                    if len(loginData) != 2:
                        accountData = {
                            "playerLoginEmail": loginEmail,
                            "playerUsername": loginData["selectedProfile"]["name"],
                            "playerUUID": loginData["selectedProfile"]["id"],
                            "playerAccessToken": loginData["accessToken"],
                            "playerClientToken": loginData["clientToken"]
                        }

                        commitWareHouse.minecraftAccounts["accountList"].append(accountData)

                        print(" * & Login complete.")
                        print(f" * & Your account player name({accountData['playerUsername']})")
                        print(f" * & Your account player uuid({accountData['playerUUID']})")
                        input(" * & Press Enter key continue... ")

                    else:
                        print(" * & Cannot certification... ")
                        print(" * & Please check your network and username or password.")
                        print(" * & Stop add account to account list.")
                        input(" * & Press Enter key continue... ")

                elif getCommand == "REMOVE":
                    print(" * ----------------------------- Remove ----------------------------- *")
                    print(" * $ Choose mode(Email|Name|UUID)")
                    print(" * $ Enter other auto exit")
                    runningMode = input(" * & --> ")

                    # 统一输入大小写
                    runningMode = runningMode.upper()

                    # 检测模式是否不存在
                    # Email 模式
                    if runningMode == "EMAIL":
                        self.__removeAccount("playerLoginEmail", "Email", commitWareHouse)

                    # Name 模式
                    elif runningMode == "NAME":
                        self.__removeAccount("playerUsername", "Name", commitWareHouse)

                    # UUID 模式
                    elif runningMode == "UUID":
                        self.__removeAccount("playerUUID", "UUID", commitWareHouse)

                elif getCommand == "SREACH" or getCommand == "SEARCH":
                    print(" * ----------------------------- Search ----------------------------- *")
                    print(" * $ Choose mode(Email|Name|UUID)")
                    print(" * $ Enter other auto exit")
                    runningMode = input(" * & --> ").upper()

                    # Email 模式
                    if runningMode == "EMAIL":
                        self.__searchAccount("playerLoginEmail", "Email", commitWareHouse)

                    # Name 模式
                    elif runningMode == "NAME":
                        self.__searchAccount("playerUsername", "Name", commitWareHouse)

                    # UUID 模式
                    elif runningMode == "UUID":
                        self.__searchAccount("playerUUID", "UUID", commitWareHouse)

                elif getCommand == "LIST":

                    # 打印列表
                    print(" * -------------------------- Account list -------------------------- *")
                    print(" * $ Print list... ")
                    print(" * $ Check list... ")
                    if len(commitWareHouse.minecraftAccounts["accountList"]) != 0:
                        for i in range(len(commitWareHouse.minecraftAccounts["accountList"])):
                            # 打印 ID
                            print(f" * ------- No. {i}")
                            # 打印信息
                            print(
                                f" * & Player email({commitWareHouse.minecraftAccounts['accountList'][i]['playerLoginEmail']})")
                            print(
                                f" * & Player name({commitWareHouse.minecraftAccounts['accountList'][i]['playerUsername']})")
                            print(
                                f" * & Player UUID({commitWareHouse.minecraftAccounts['accountList'][i]['playerUUID']})")
                            print(f" * & Player password(** You don't have access **)")
                        print(" * ------- End print")
                    else:
                        print(" * $ No account.")

                elif getCommand == "QUIT" or getCommand == "Q":

                    # 离开
                    break

                elif getCommand == "":

                    # 继续
                    continue

                else:
                    print(" * [LitsMine] Unkown account command.")
                    print(" * [LitsMine] Auto exit")
                    input(" * [LitsMine] Press Enter key continue... ")
                    break
